<?php

define('TIME_UTC', time());

function getuids() {
    return array(1,3,7);
}

function getmgsarr() {
    return  array(
        0 => array( //文章
            // 用户1
            1 => array('1-a %title', '1-b', '1-c', '1-d', '1-e',
                    '1-f', '1-g', '1-h', '1-i', '1-j','1-k',
                    '1-l', '1-m', '1-n', '1-o', '1-p', '1-q',
                    '1-r', '1-s', '1-t'),
            // 用户3
            3 => array('3-a', '3-b', '3-c', '3-d', '3-e',
                    '3-f', '3-g', '3-h', '3-i', '3-j','3-k',
                    '3-l', '3-m', '3-n', '3-o', '3-p', '3-q',
                    '3-r', '3-s', '3-t'),
            // 用户7
            7 => array('7-a', '7-b', '7-c', '7-d', '7-e',
                    '7-f', '7-g', '7-h', '7-i', '7-j','7-k',
                    '7-l', '7-m', '7-n', '7-o', '7-p', '7-q',
                    '7-r', '7-s', '7-t'),
        ),
        1 => array( // 产品
            1 => array('product-1-a', 'product-1-b', 'product-1-c', 'product-1-d', 'product-1-e',
                    'product-1-f', 'product-1-g', 'product-1-h', 'product-1-i', 'product-1-j','product-1-k',
                    'product-1-l', 'product-1-m', 'product-1-n', 'product-1-o', 'product-1-p', 'product-1-q',
                    'product-1-r', 'product-1-s', 'product-1-t'),
            3 => array('product-3-a', 'product-3-b', 'product-3-c', 'product-3-d', 'product-3-e',
                    'product-3-f', 'product-3-g', 'product-3-h', 'product-3-i', 'product-3-j','product-3-k',
                    'product-3-l', 'product-3-m', 'product-3-n', 'product-3-o', 'product-3-p', 'product-3-q',
                    'product-3-r', 'product-3-s', 'product-3-t'),
            7 => array('product-7-a', 'product-7-b', 'product-7-c', 'product-7-d', 'product-7-e',
                    'product-7-f', 'product-7-g', 'product-7-h', 'product-7-i', 'product-7-j','product-7-k',
                    'product-7-l', 'product-7-m', 'product-7-n', 'product-7-o', 'product-7-p', 'product-7-q',
                    'product-7-r', 'product-7-s', 'product-7-t'),
        ),
        3 => array( // 商家资料
            1 => array('shopinfo-1-a', 'shopinfo-1-b', 'shopinfo-1-c', 'shopinfo-1-d', 'shopinfo-1-e',
                    'shopinfo-1-f', 'shopinfo-1-g', 'shopinfo-1-h', 'shopinfo-1-i', 'shopinfo-1-j','shopinfo-1-k',
                    'shopinfo-1-l', 'shopinfo-1-m', 'shopinfo-1-n', 'shopinfo-1-o', 'shopinfo-1-p', 'shopinfo-1-q',
                    'shopinfo-1-r', 'shopinfo-1-s', 'shopinfo-1-t'),
            3 => array('shopinfo-3-a', 'shopinfo-3-b', 'shopinfo-3-c', 'shopinfo-3-d', 'shopinfo-3-e',
                    'shopinfo-3-f', 'shopinfo-3-g', 'shopinfo-3-h', 'shopinfo-3-i', 'shopinfo-3-j','shopinfo-3-k',
                    'shopinfo-3-l', 'shopinfo-3-m', 'shopinfo-3-n', 'shopinfo-3-o', 'shopinfo-3-p', 'shopinfo-3-q',
                    'shopinfo-3-r', 'shopinfo-3-s', 'shopinfo-3-t'),
            7 => array('shopinfo-7-a', 'shopinfo-7-b', 'shopinfo-7-c', 'shopinfo-7-d', 'shopinfo-7-e',
                    'shopinfo-7-f', 'shopinfo-7-g', 'shopinfo-7-h', 'shopinfo-7-i', 'shopinfo-7-j','shopinfo-7-k',
                    'shopinfo-7-l', 'shopinfo-7-m', 'shopinfo-7-n', 'shopinfo-7-o', 'shopinfo-7-p', 'shopinfo-7-q',
                    'shopinfo-7-r', 'shopinfo-7-s', 'shopinfo-7-t'),
        )
    );
}

class WoguToolsAction extends CommonAction
{
    public function comment() {
        if(isset($_POST['docomment'])) {
            $ids = explode(',', $_POST['id']);
            $catetype = intval($_POST['catetype']);
            $msgsarr = getmgsarr();
            $msgs = $msgsarr[$catetype];
            $uids = getuids();

            foreach($ids as $id) {
                for($i = 0; $i < 20; $i++) {
                    $uid = $uids[array_rand($uids)];
                    $msg = $msgs[$uid][array_rand($msgs[$uid])];
                    if($catetype == 0) {
                        $this->artcomment($uid, $msg, intval($id));
                    } elseif($catetype == 1) {
                        $this->productcomment($uid, $msg, intval($id));
                    } elseif($catetype == 3) {
                        $this->shopcomment($uid, $msg, intval($id));
                    }
                }
            }
        }

        $this->display();
    }

    private function shopcomment($uid, $msg, $share_id) {
        $share = M('WoguUserShop')->find(array('id' => $share_id));
        $msg = str_replace('%title', $share['name'], $msg);
        $data = array();
        $data['content'] =  $msg;
        $data['uid'] = $uid;
        $data['parent_id'] = 0;
        $data['share_id'] = $share_id;
        $data['create_time'] = TIME_UTC;
        $comment_id = M('WoguUserShopComment')->add($data);

        //分享评论数量加1
        M('WoguUserShop')->query('UPDATE '.C("DB_PREFIX").'wogu_user_shop
            SET comment_count = comment_count + 1
            WHERE id = '.$share_id);

        // 转发
        $sharedata = array(
            'uid' => $uid,
            'content' => '我分享了商家资料《<a href="/shopinfo.php?action=show&id='.$share_id.'">'.$share['name'].'》</a><p><img width="257" src="'.$share['img'].'"/></p>',
            'create_time' => TIME_UTC,
            'day_time' => getTodayTime(),
            'status' => 1,
        );
        M('share')->add($sharedata);

        // 关注
        $comments = M('WoguUserShopComment')->select(array('share_id' => $share_id));
        if(!empty($comments)) {
            $uids[] = $share['id'];
            foreach ($comments as $v) {
                $uids[] = $v['uid'];
            }
            $uids = array_unique($uids);
            foreach ($uids as $fuid) {
                if($uid != $fuid) {
                    $count = M('UserFollow')->query('SELECT COUNT(*) AS num FROM '.C("DB_PREFIX").'user_follow WHERE f_uid='.$fuid.' AND uid='.$uid);
                    $count = $count[0]['num'];
                    if($count == 0) {
                        $data = array('f_uid' => $fuid, 'uid' => $uid, 'create_time' => TIME_UTC);
                        M('UserFollow')->add($data);
                    }
                }
            }
        }
    }

    private function productcomment($uid, $msg, $share_id) {
        $share = M('WoguProduct')->find(array('id' => $share_id));
        $msg = str_replace('%title', $share['title'], $msg);
        $data = array();
        $data['content'] =  $msg;
        $data['uid'] = $uid;
        $data['parent_id'] = 0;
        $data['share_id'] = $share_id;
        $data['create_time'] = TIME_UTC;
        $comment_id = M('WoguProductComment')->add($data);

        //分享评论数量加1
        M('WoguProduct')->query('UPDATE '.C("DB_PREFIX").'wogu_product
            SET comment_count = comment_count + 1
            WHERE id = '.$share_id);

        // 转发
        $sharedata = array(
            'uid' => $uid,
            'content' => '我分享了商品《<a href="/product.php?action=show&id='.$share_id.'">'.$share['title'].'》</a><p><img width="257" src="'.$share['img'].'"/></p>',
            'create_time' => TIME_UTC,
            'day_time' => getTodayTime(),
            'status' => 1,
        );
        M('share')->add($sharedata);

        // 关注
        $comments = M('WoguProductComment')->select(array('share_id' => $share_id));
        if(!empty($comments)) {
            $uids = array();
            if($share['uid']) $uids[] = $share['uid'];
            foreach ($comments as $v) {
                $uids[] = $v['uid'];
            }
            $uids = array_unique($uids);
            foreach ($uids as $fuid) {
                if($uid != $fuid) {
                    $count = M('UserFollow')->query('SELECT COUNT(*) AS num FROM '.C("DB_PREFIX").'user_follow WHERE f_uid='.$fuid.' AND uid='.$uid);
                    $count = $count[0]['num'];
                    if($count == 0) {
                        $data = array('f_uid' => $fuid, 'uid' => $uid, 'create_time' => TIME_UTC);
                        M('UserFollow')->add($data);
                    }
                }
            }
        }
    }

    private function artcomment($uid, $msg, $share_id) {
        $share = M('article')->find(array('id' => $share_id));
        $msg = str_replace('%title', $share['title'], $msg);
        $data = array();
        $data['content'] =  $msg;
        $data['uid'] = $uid;
        $data['parent_id'] = 0;
        $data['share_id'] = $share_id;
        $data['create_time'] = TIME_UTC;
        $comment_id = M('ArticleComment')->add($data);

        //分享评论数量加1
        M('article')->query('UPDATE '.C("DB_PREFIX").'article
            SET comment_count = comment_count + 1
            WHERE id = '.$share_id);

        // 转发
        $sharedata = array(
            'uid' => $uid,
            'content' => '我分享了文章《<a href="/article.php?action=show&id='.$share_id.'">'.$share['title'].'》</a><p><img width="257" src="'.$share['img'].'"/></p>',
            'create_time' => TIME_UTC,
            'day_time' => getTodayTime(),
            'status' => 1,
        );
        M('share')->add($sharedata);

        // 关注
        $comments = M('ArticleComment')->select(array('share_id' => $share_id));
        if(!empty($comments)) {
            $uids = array();
            if($share['uid']) $uids[] = $share['uid'];
            foreach ($comments as $v) {
                $uids[] = $v['uid'];
            }
            $uids = array_unique($uids);
            foreach ($uids as $fuid) {
                if($uid != $fuid) {
                    $count = M('UserFollow')->query('SELECT COUNT(*) AS num FROM '.C("DB_PREFIX").'user_follow WHERE f_uid='.$fuid.' AND uid='.$uid);
                    $count = $count[0]['num'];
                    if($count == 0) {
                        $data = array('f_uid' => $fuid, 'uid' => $uid, 'create_time' => TIME_UTC);
                        M('UserFollow')->add($data);
                    }
                }
            }
        }
    }

    public function realname() {
        if($_GET['op'] == 's' || $_GET['op'] == 'p') {
            $uid = $_GET['id'];
            $table = C("DB_PREFIX") . ($_GET['op'] == 's' ? 'wogu_realname_shop' : 'wogu_realname_person');
            $flag = $_GET['flag'] == 2 ? 2 : 3;
            if($_GET['op'] == 's' && $flag == 2) {
                $tmp = M()->query('SELECT * FROM '.C("DB_PREFIX").'wogu_realname_shop WHERE uid='.$uid);
                $info = $tmp[0];
                // 店铺名称检测
                $tmp = M()->query('SELECT * FROM '.C("DB_PREFIX").'wogu_user_shop WHERE name=\''.$info['shopname'].'\' AND uid!='.$uid." AND province='{$info['province']}' AND city='{$info['city']}' AND notshow=0");
                $r = $tmp[0];
                if(!empty($r)) {
                    if($r['uid'] == 0) {
                        M()->query("UPDATE ".C("DB_PREFIX")."wogu_user_shop SET notshow=1 WHERE id='{$r['id']}'");
                    } else {
                        $this->error("已经有同名的火锅公司存在！", $_SERVER['HTTP_REFERER']);
                        exit;
                    }
                }

                $tmp = M()->query('SELECT COUNT(*) AS num FROM '.C("DB_PREFIX").'wogu_user_shop WHERE uid='.$uid);
                if($tmp[0]['num'] > 0) {
                    M()->query('UPDATE '.C("DB_PREFIX")."wogu_user_shop SET name='{$info['shopname']}',province='{$info['province']}',city='{$info['city']}',stype='{$info['stype']}',auth_type='{$info['auth_type']}',lat='{$info['lat']}',lng='{$info['lng']}',v2='{$info['v2']}',bzj='{$info['bzj']}' WHERE uid={$uid}");
                } else {
                    M()->query('INSERT INTO '.C("DB_PREFIX")."wogu_user_shop (uid,name,province,city,stype,auth_type,lat,lng,v2,bzj) VALUES('{$uid}','{$info['shopname']}', '{$info['province']}', '{$info['city']}', '{$info['stype']}', '{$info['auth_type']}', '{$info['lat']}', '{$info['lng']}', '{$info['v2']}', '{$info['bzj']}')");
                }
            }

            M()->query('UPDATE '.$table.' SET flag='.$flag.' WHERE uid='.$uid);
            $field = $_GET['op'] == 's' ? 'realname_shop' : 'realname_person';
            $uflag = $flag == 2 ? 1 : 0;
            $wogu_medal = $flag == 2 ? 1 : 0;
            M()->query('UPDATE '.C("DB_PREFIX").'user SET '.$field.'='.$uflag.',user_type='.($_GET['op'] == 's' ? 1 : 0).',wogu_medal='.$wogu_medal.",v2='{$info['v2']}}',bzj='{$info['bzj']}' WHERE uid=".$uid);
            if($flag == 2) {
                $tmp = M()->query('SELECT * FROM '.C("DB_PREFIX").'user WHERE uid='.$uid);
                if($tmp[0]['inviter'] > 0) {
                    M()->query('UPDATE '.C("DB_PREFIX").'user SET hzl_num=hzl_num+1,coupon_num=coupon_num+1 WHERE uid='.$tmp[0]['inviter']);
                }
            }

    		$result = M()->query("INSERT INTO ".C("DB_PREFIX")."user_notice (uid, type, num, create_time) VALUES($uid,6,1,'".time()."')");
    		if(!$result)
    			M()->query("UPDATE ".C("DB_PREFIX")."user_notice SET num = num + 1, create_time='".time()."' WHERE uid=$uid AND type = 6");
    	    $msg = $flag == 2 ? '恭喜！您的实名认证请求已经通过审核！' : '很抱歉的通知您，你的实名认证未通过，请检查资料后再次提交！';
            M()->query("INSERT INTO ".C("DB_PREFIX")."sys_notice (uid, title, content, create_time) VALUES($uid,'实名认证结果通知','{$msg}','".time()."')");
        } elseif ($_GET['op'] == 'realaddr') {
            $uid = $_GET['id'];
            M()->query('UPDATE '.C("DB_PREFIX").'user SET wogu_medal=2 WHERE uid='.$uid);
        }

		$model = M();
		$sql = 'SELECT COUNT(*) AS tcount FROM '.C("DB_PREFIX").'wogu_realname_shop WHERE 1';
		$count = $model->query($sql);
		$count = $count[0]['tcount'];

		$sql = 'SELECT * FROM '.C("DB_PREFIX").'wogu_realname_shop';
		$this->_sqlList($model,$sql,$count,array(),'dateline');
		$this->display();
    }

    public function withdraw() {
		$model = M();
		if($_GET['op'] == 'check') {
		    $id = intval($_GET['id']);
		    $flag = intval($_GET['flag']);
		    $withdraw = M('WoguWithdraw')->find(array('id' => $id));
		    if(!$withdraw) {
		        $this->error("记录不存在！", $_SERVER['HTTP_REFERER']);
		        exit;
		    }
		    M()->query('UPDATE '.C("DB_PREFIX").'wogu_withdraw SET flag='.$flag.' WHERE id='.$id);

    		$result = M()->query("INSERT INTO ".C("DB_PREFIX")."user_notice (uid, type, num, create_time) VALUES({$withdraw['uid']},6,1,'".time()."')");
    		if(!$result)
    			M()->query("UPDATE ".C("DB_PREFIX")."user_notice SET num = num + 1, create_time='".time()."' WHERE uid={$withdraw['uid']} AND type = 6");
    	    $msg = $flag == 1 ? '恭喜！您的提现申请已经审核通过！' : '很抱歉的通知您，您的提现申请未审核通过！';
            M()->query("INSERT INTO ".C("DB_PREFIX")."sys_notice (uid, title, content, create_time) VALUES({$withdraw['uid']},'提现申请审核结果通知','{$msg}','".time()."')");
            $this->success("操作成功！", $_SERVER['HTTP_REFERER']);
            exit;
		}

		$where = 'flag='.intval($_GET['flag']);
		$sql = 'SELECT COUNT(*) AS tcount FROM '.C("DB_PREFIX").'wogu_withdraw WHERE '.$where;
		$count = $model->query($sql);
		$count = $count[0]['tcount'];

		$sql = 'SELECT * FROM '.C("DB_PREFIX").'wogu_withdraw WHERE '.$where;
		$this->_sqlList($model,$sql,$count,array(),'id');
        if($this->list) {
		    $uids = array();
    		foreach($this->list as $v) {
    		    $uids[] = $v['uid'];
    		}

    		$uids = array_unique($uids);
    		$sql = 'SELECT uid,user_name FROM '.C("DB_PREFIX").'user WHERE uid IN('.implode(',', $uids).')';
    		$tmp = $model->query($sql);
    		foreach($tmp as $v)
    		    $users[$v['uid']] = $v;

    	    $this->assign('users', $users);
        }
		$this->display();
    }

    public function rss() {
//        $sql = 'SELECT * FROM '.C("DB_PREFIX").'wogu_user_shop';
//        $tmp = M()->query($sql);
//        foreach($tmp as $v) {
//            if(empty($catenames[$v['cate_id']])) {
//                $cat = M('GoodsCategory')->find(array('where' => array('cate_id' => $v['cate_id'])));
//                $catenames[$v['cate_id']] = $cat['cate_name'];
//            }
//            $desc = '商家名称：'.$v['name'].(!empty($v['telphone']) ? ',电话号码：'.$v['telphone'] : '').(!empty($v['mobile']) ? ',手机号码：'.$v['mobile'] : '').',地址：'.$v['address'].',分类：'.$catenames[$v['cate_id']].',';
//            $orderby = $v['img'] == '/public/v1/img/default.jpg' ? 1 : 0;
//            M()->query('UPDATE '.C("DB_PREFIX")."wogu_user_shop SET seo_desc='{$desc}',orderby='{$orderby}' WHERE id={$v['id']}");
//        }
//        exit;

        $fp = fopen('../rss.txt', 'w+');
        $sql = 'SELECT id FROM '.C("DB_PREFIX").'wogu_user_shop';
        $tmp = M()->query($sql);
        foreach($tmp as $v)
            fwrite($fp, 'http://huoguoge.com/shopinfo.php?action=show&id='.$v['id']."\r\n");

        $sql = 'SELECT id FROM '.C("DB_PREFIX").'article';
        $tmp = M()->query($sql);
        foreach($tmp as $v)
            fwrite($fp, 'http://huoguoge.com/article.php?action=show&id='.$v['id']."\r\n");
        fclose($fp);
        echo 'ok';
    }

    public function feedback() {
        $model = M();
		$where = '1';
		$sql = 'SELECT COUNT(*) AS tcount FROM '.C("DB_PREFIX").'wogu_feedback2 WHERE '.$where;
		$count = $model->query($sql);
		$count = $count[0]['tcount'];

		$sql = 'SELECT * FROM '.C("DB_PREFIX").'wogu_feedback2 WHERE '.$where;
		$this->_sqlList($model,$sql,$count,array(),'id');
		$this->display();
    }

    public function importshop() {
        if($_POST['doimport']) {
            //cate_id,name,province,city,img,mobile,mobile2,telphone,telphone2,address
            $data = explode("\r\n", $_POST['data']);
            foreach($data as $v) {
                if(!empty($v)) {
                    $arr = explode(',', $v);
                    if(count($arr) != 10) continue;
                    list($cate_id, $name, $province, $city, $img, $mobile, $mobile2, $telphone, $telphone2, $address) = $arr;
                    $mobile = trim($mobile);
                    $mobile2 = trim($mobile2);
                    $telphone = trim($telphone);
                    $telphone2 = trim($telphone2);

                    if(empty($catenames[$cate_id])) {
                        $cat = M('GoodsCategory')->find(array('where' => array('cate_id' => $cate_id)));
                        $catenames[$cate_id] = $cat['cate_name'];
                    }
                    $desc = '商家名称：'.$name.(!empty($telphone) ? ',电话号码：'.$telphone : '').(!empty($mobile) ? ',手机号码：'.$mobile : '').',地址：'.$address.',分类：'.$catenames[$cate_id].',';
                    $content = '<p><img src="'.$img.'" alt="'.$name.'"/></p>';
                    list($width, $height) = getimagesize('..'.$img);
                    $create_time = time();
                    M()->query("INSERT INTO ".C("DB_PREFIX")."wogu_user_shop (uid,cate_id,name,seo_desc,province,city,img,content,width,height,create_time,mobile,mobile2,telphone,telphone2,address) VALUES(0,'{$cate_id}','{$name}','{$desc}','{$province}','{$city}','{$img}','{$content}','{$width}','{$height}','{$create_time}','{$mobile}','{$mobile2}','{$telphone}','{$telphone2}','{$address}')");
                }
            }
        }

        $this->display();
    }
}

function getTodayTime()
{
    static $today_time = NULL;
    if($today_time === NULL)
        $today_time = mktime(0,0,0,date('m'),date('d'),date('Y')) - date('Z');
    return $today_time;
}